from app.database.postgre import SessionDep, col
from app.database.models import Account, SystemBoard
from app.models import responses
from app.models.system_boards import (SystemBoardsListParams, CreateSystemBoardJSON, DeleteSystemBoardJSON,
                                      BatchDeleteBoardsJSON)


async def get_system_boards_list(
        account: Account,
        query_params: SystemBoardsListParams,
        session: SessionDep
):
    """获取分页后的系统公告"""
    # 构建查询参数
    page = query_params.page
    if account.has_admin_permission:
        page_size = min(query_params.page_size, 50)
    else:
        page_size = min(query_params.page_size, 10)
    order_by = col(SystemBoard.create_time).desc()

    # 对数据进行分页
    query = session.query(SystemBoard).order_by(order_by)
    total_count = query.count()
    total_pages = (total_count + page_size - 1) // page_size

    offset = (page - 1) * page_size
    paginated_query = query.offset(offset).limit(page_size)
    paginated_boards = paginated_query.all()

    # 构建结果列表
    response_list = []
    for board in paginated_boards:
        publisher = Account.get_by_aid(session, board.account_id)
        if publisher:
            response_list.append({
                'id': board.id,
                'content': board.content,
                'create_at': board.create_time.timestamp(),
                'author': publisher.username,
                'avatar': publisher.avatar
            })

    return responses.SuccessResponse(
        data={
            'total': total_count,
            'total_pages': total_pages,
            'page': page,
            'page_size': len(response_list),
            'list': response_list
        }
    )


async def create_system_board(
        admin_account: Account,
        json_data: CreateSystemBoardJSON,
        session: SessionDep
):
    """创建公告"""
    new_board = SystemBoard(content=json_data.content, account_id=admin_account.aid)
    try:
        session.add(new_board)
        session.commit()
        session.refresh(new_board)
    except Exception as e:
        session.rollback()
        raise e

    response_data = {
        'id': new_board.id,
        'content': new_board.content,
        'create_at': new_board.create_time.timestamp(),
        'author': new_board.account.username,
        'avatar': new_board.account.avatar
    }

    return responses.SuccessResponse(msg='发布成功', data=response_data)


async def delete_board_by_id(admin_account: Account, json_data: DeleteSystemBoardJSON, session: SessionDep):
    """删除单条公告"""
    board = session.get(SystemBoard, json_data.board_id)
    if not board:
        return responses.Response1103()

    if not admin_account.has_super_permission and board.account_id != admin_account.aid:
        return responses.Response1102()

    session.delete(board)
    session.commit()

    return responses.SuccessResponse(msg='删除成功', data=board.model_dump(include={'id'}))


async def delete_board_by_ids(admin_account: Account, json_data: BatchDeleteBoardsJSON, session: SessionDep):
    """批量删除系统公告"""
    boards = session.query(SystemBoard).filter(col(SystemBoard.id).in_(json_data.board_ids)).all()
    if not boards:
        return responses.SuccessResponse(msg='没有找到指定的公告', data={'count': 0, 'ids': []})

    if admin_account.has_super_permission:
        deleted_ids = [board.id for board in boards]
    else:
        deleted_ids = [board.id for board in boards if board.account_id == admin_account.aid]

    session.query(SystemBoard).filter(col(SystemBoard.id).in_(deleted_ids)).delete(synchronize_session=False)
    session.commit()

    return responses.SuccessResponse(msg='选中的公告已删除', data={
        'count': len(deleted_ids),
        'ids': deleted_ids
    })


async def clear_all_system_boards(admin_account, session: SessionDep):
    """清空所有的系统公告"""
    boards = session.query(SystemBoard).all()
    if not boards:
        return responses.SuccessResponse(msg='没有公告可清空')

    if admin_account.has_super_permission:
        session.query(SystemBoard).delete(synchronize_session=False)
        session.commit()
    else:
        session.query(SystemBoard).filter(
            SystemBoard.account_id == admin_account.aid
        ).delete(synchronize_session=False)
        session.commit()

    return responses.SuccessResponse(msg='公告已清空')
